package com.haidechizi.validate.global;

import com.haidechizi.validate.holder.DictHolder;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public String handlerException(HttpServletRequest request,
                                   Exception exception) {
        BindingResult bindResult = null;
        if (exception instanceof BindException) {
            bindResult = ((BindException) exception).getBindingResult();
        } else if (exception instanceof MethodArgumentNotValidException) {
            bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        }
        String message;
        if (bindResult != null && bindResult.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            bindResult.getAllErrors().forEach(objectError -> {
                String defaultMessage = objectError.getDefaultMessage();
                sb.append(defaultMessage).append("\n");
            });
            message = DictHolder.getMessage(sb.toString());
        } else {
            message = "系统繁忙，请稍后重试...";
        }
        return message;
    }
}
